package com.stephen.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by stephen on 2021-03-28 10:56 .
 * Description:
 */
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // ServletContext为不同Servlet所共享,可以用来传递参数,setAttribute和getAttribute方法
        ServletContext context = this.getServletContext();
        context.setAttribute("name","李四");
        // HttpServletRequest不会在不同的Servlet中传递
        req.setAttribute("username","张三");
        // resp的编码设置要在PrintWriter之前,否则不会生效
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.print("Hello Servlet 名字: " + req.getAttribute("username"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
